<template>
  <div class="contractTmp-box">
    <div class="label-box-content">
      <el-row :gutter="30" type="flex">
        <el-col :span="7">
          <NewCard title="一级类别">
            <div class="leftMenu">
              <el-tag
                :key="index"
                v-for="(type, index) in tableData"
                :disable-transitions="false"
                :class="{ tagActive: currentIndex === index }"
                @click="onRowClick(type, index)"
              >
                <p
                  @dblclick="dblclickInput(index)"
                  v-if="tagInput === index ? false : true"
                >
                  {{ type.name }}
                </p>
                <el-input
                  v-else
                  v-model="type.name"
                  @keyup.enter.native="handleInput(type, type.name)"
                  @blur="handleInput(type, type.name)"
                  ref="dbtagInput"
                  clearable
                >
                </el-input>
                <p class="tag-icon">
                  <el-upload
                    ref="upload"
                    list-type="picture"
                    accept=".jpg,.png"
                    :action="'#'"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="getFile"
                    :before-remove="() => false"
                    @click.native="getFileId(type)"
                  >
                    <img :src="type.icon" alt="" />
                  </el-upload>
                </p>
              </el-tag>
              <ComAddButton
                v-hasPermi="['work:contractType:add']"
                label="添加一级类别"
                @Event-blurInput="handleInputConfirm"
              ></ComAddButton>
            </div>
          </NewCard>
        </el-col>
        <el-col :span="7">
          <NewCard title="二级类别">
            <div class="leftMenu">
              <el-tag
                :key="index"
                v-for="(jobTitle, index) in scendtable"
                :disable-transitions="false"
                :class="{ tagActive: sencendIndex === index }"
                @click="secendClick(jobTitle, index)"
              >
                <p
                  @dblclick="dblclickJobInput(index)"
                  v-if="jobInput === index ? false : true"
                >
                  {{ jobTitle.name }}
                </p>
                <el-input
                  v-else
                  v-model="jobTitle.name"
                  @keyup.enter.native="handleJobInput(jobTitle, jobTitle.name)"
                  @blur="handleJobInput(jobTitle, jobTitle.name)"
                  ref="dbJobInput"
                  clearable
                >
                </el-input>
                <div class="icon_box">
                  <!-- 合同类别比对词 -->
                  <svg-icon icon-class="form" @click="clickThanWords"/>
                  <!-- 合同上传按钮 -->
                  <p class="upload-icon" v-hasPermi="['doc:scontract:uploadContractFiles']">
                    <el-upload
                      ref="upload"
                      accept=".docx"
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      :on-change="(file, fileList) => {uploadContract(file, fileList, jobTitle, index)}"
                      :before-remove="() => false"
                      multiple
                    >
                      <i class="el-icon-upload"></i>
                    </el-upload>
                  </p>
                </div>
              </el-tag>
              <!-- <ComAddButton
                label="添加二级类别"
                @Event-blurInput="handleJobConfirm"
              ></ComAddButton> -->
              <ComAddButtonTwo
                v-hasPermi="['work:contractType:add']"
                label="添加二级类别"
                @Event-blurInput="handleJobConfirm"
              >
              </ComAddButtonTwo>
            </div>
          </NewCard>
        </el-col>
        <el-col :span="10">
          <NewCard title="合同名称">
            <div class="">
              <el-table
                :data="thridtable"
                :show-header="false"
                style="width: 100%"
                @cell-dblclick="tabClick"
                :row-class-name="tableRowClassName"
                :border="border"
                :highlight-current-row="highlight"
              >
                <el-table-column label="Name" prop="name">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex">
                      <el-input
                        v-model="scope.row.name"
                        maxlength="300"
                        placeholder="请输入原因"
                        size="mini"
                        @blur="inputBlur(scope.row)"
                      />
                    </span>
                    <span v-else>{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <div class="edit-box">
                      <span class="emlemt" @click="contentlist(scope.row)"
                        >内容</span
                      >
                      <span
                        v-hasPermi="['work:contractVerify:edit']"
                        class="info"
                        style="margin-left: 10px"
                        @click="
                          factor = true;
                          factorlistclick(scope.row);
                        "
                        >要素</span
                      >
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div>
              <el-button
                v-hasPermi="['doc:scontract:add']"
                class="hetongbtn"
                @click="addcontenname"
                >+添加合同名称</el-button
              >
            </div>
          </NewCard>
        </el-col>

        <!-- 合同信息抽屉 -->
        <el-drawer
          ref="drwaer"
          size="80%"
          :visible="content"
          :direction="direction"
          :before-close="contentClose"
        >
          <template #title>
            <div class="title-box">
              <div class="left">
                <h1 class="titile">
                  <img
                    class="icon"
                    :src="require('@/wss/assets/image/icon/cardLeft.png')"
                    alt=""
                  />

                  <span>合同内容</span>
                </h1>
              </div>
            </div>
          </template>
          <div class="drawerMain">
            <el-row :gutter="20">
              <el-col :span="12">
                <NewCard title="内容" :border="true">
                  <div class="lineItem">
                    <div
                      :class="statusactiv == index ? 'isbgc' : ''"
                      v-for="(item, index) in contractList.info"
                      :key="index"
                      @click="clickinfo(contractList, index)"
                    >
                      <div class="divinfo">
                        <p v-html="item.replace(/\r/g,'</p><p>' )"></p>
                        
                      </div>
                    </div>
                  </div>
                </NewCard>
              </el-col>

              <div class="editmain">
                <el-col :span="12">
                  <NewCard title="编辑" :border="true">
                    <el-input
                      v-model="contenttitle"
                      class="inputtitle"
                      placeholder="请输入内容"
                    ></el-input>
                    <WangEditor
                      class="wangeditor"
                      :wangkey="1"
                      ref="wangEditor"
                      :list="currentContent"
                    >
                    </WangEditor>
                    <SubBtn>
                      <template slot="btn">
                        <el-button round @click="deletinfo(contractList)"
                          >删除</el-button
                        >
                        <!-- <el-button round @click="preservation(contractList)"
                        >新增并保存</el-button
                      > -->
                        <el-button
                          class="addBtn"
                          @click="addscontractinfo(contractList)"
                          round
                          >{{currentContent.length?'修改':'新增并继续'}}</el-button
                        >
                      </template>
                    </SubBtn>
                  </NewCard>
                </el-col>
              </div>
            </el-row>
          </div>
        </el-drawer>

        <!-- 合同名称 -->
        <!-- <el-drawer
          :visible.sync="contentname"
          :direction="direction"
          size="50%"
          :before-close="contentnameClose"
        >
          <template #title>
            <div class="title-box">
              <div class="left">
                <h1 class="titile">
                  <img
                    class="icon"
                    :src="require('@/wss/assets/image/icon/cardLeft.png')"
                    alt=""
                  />
                  <span>合同内容</span>
                </h1>
              </div>
            </div>
          </template>
          <div class="drawerMain">
            <el-row :gutter="20">
              <el-col :span="20">
                <el-form
                  :model="contentForm"
                  :rules="contenrules"
                  ref="contentForm"
                  label-width="100px"
                  class="demo-ruleForm"
                >
                  <el-form-item label="合同名称" prop="element">
                    <el-input v-model="contentForm.name"></el-input>
                  </el-form-item>
                  <el-form-item label="是否添加要素" prop="delivery">
                    <el-switch v-model="contentForm.delivery"></el-switch>
                  </el-form-item>
                  <el-form-item label="合同内容" prop="keypoint">
                    <Editor
                      ref="editor"
                      :height="200"
                      :value="currentValue"
                    ></Editor>
                
                  </el-form-item>
                
                  <SubBtn>
                    <template slot="btn">
                      <el-button
                        round
                        class="addBtn"
                        @click="addContentname(contentForm)"
                        >确定</el-button
                      >
                    </template>
                  </SubBtn>
                </el-form>
              </el-col>
            </el-row>
          </div>
        </el-drawer> -->
        
        <!-- 合同要素抽屉 -->
        <el-drawer
          size="80%"
          :visible.sync="factor"
          :direction="direction"
          :before-close="factorClose"
        >
          <template #title>
            <div class="title-box">
              <div class="left">
                <h1 class="titile">
                  <img
                    class="icon"
                    :src="require('@/wss/assets/image/icon/cardLeft.png')"
                    alt=""
                  />

                  <span>要素信息</span>
                </h1>
              </div>
            </div>
          </template>
          <div class="yasuinfo">
            <el-row :gutter="30" type="flex">
              <el-col :span="16">
                <NewCard :isright="true" title="内容">
                  <div class="businTalbe">
                    <ComTable
                      @handleSizeChange="handleSizeChange"
                      @handleCurrentChange="handleCurrentChange"
                      :config="config"
                      :pagination="{
                        total: pageing.total,
                        pageNum: pageing.pageNum,
                        pageSize: pageing.pageSize,
                      }"
                      :list="factortable"
                      :modes="tableModes"
                      @EventRowClick="RowClickFn"
                    >
                    </ComTable>
                  </div>
                  <div class="copypaste">
                    <el-button class="copy-email" @click="copy">
                      复制要素
                    </el-button>
                    <!-- <span>|</span> -->
                    <el-button class="" @click="paste">粘贴要素</el-button>
                  </div>
                </NewCard>
              </el-col>
              <el-col :span="10">
                <div class="infoExpert">
                  <NewCard :isright="true" title="详情">
                    <div class="perInfo">
                      <el-form
                        :model="ruleForm"
                        :rules="rules"
                        ref="ruleForm"
                        label-width="100px"
                        class="demo-ruleForm"
                      >
                        <el-form-item label="要素名称" prop="element">
                          <el-input v-model="ruleForm.element"></el-input>
                        </el-form-item>
                        <el-form-item label="要素同义词" prop="synonym">
                          <el-input v-model="ruleForm.synonym"></el-input>
                        </el-form-item>
                        <el-form-item label="要素说明" prop="keypoint">
                          <el-input
                            type="textarea"
                            :autosize="{ minRows: 10, maxRows: 20 }"
                            v-model="ruleForm.keypoint"
                          ></el-input>
                        </el-form-item>
                      </el-form>
                      <SubBtn>
                        <template slot="btn">
                          <el-button round @click="deleteinfo(ruleForm)"
                            >删除</el-button
                          >

                          <el-button round @click="resetForm">重设</el-button>
                          <el-button
                            class="addBtn"
                            @click="submitForm('ruleForm')"
                            round
                            >{{this.ysid?'修改':'新增并继续'}}</el-button
                          >
                        </template>
                      </SubBtn>
                      <!-- <el-form-item>
                              <el-button
                                type="primary"
                                size="mini"
                                @click="submitForm('ruleForm')"
                                >确定</el-button
                              >
                              <el-button
                                @click="resetForm"
                                size="mini"
                                type="primary"
                                >重置</el-button
                              >
                            </el-form-item> -->
                    </div>
                  </NewCard>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-drawer>

        <!-- 合同类别比对词抽屉 -->
        <el-drawer
          ref="drwaer"
          size="40%"
          :visible="thanWordShow"
          :direction="direction"
          :before-close="thanWordClose">
          <template #title>
            <div class="title-box">
              <div class="left">
                <h1 class="titile">
                  <img
                    class="icon"
                    :src="require('@/wss/assets/image/icon/cardLeft.png')"
                    alt=""
                  />
                  <span>合同类别比对词</span>
                </h1>
              </div>
            </div>
          </template>
          <!-- 编辑文本域 -->
          <div class="thanWordBox" v-if="secendData">
            <el-input
              class="thanWordInput"
              type="textarea"
              :rows="8"
              placeholder="请输入..."
              v-model="secendData.keywords">
            </el-input>
          </div>

          <!-- 底部按钮 -->
          <SubBtn>
            <template slot="btn">
              <el-button round @click="thanWordCancel">取消</el-button>
              <el-button class="addBtn" round @click="thanWordConfirm">确定</el-button>
            </template>
          </SubBtn>
        </el-drawer>
      </el-row>
    </div>
  </div>
</template>
<script>
import NewCard from "@/wss/components/newCard.vue";
import Comdrawer from "@/wss/components/Comdrawer.vue";
import ComAddButton from "@/wss/components/tablecomponents.vue";
import ComAddButtonTwo from "@/wss/components/tablecomponentsTwo.vue";

import ComTable from "@/wss/components/comTable.vue";
import WangEditor from "@/wss/components/wangEditor.vue";
import SubBtn from "@/wss/components/subBtn.vue";
import Editor from "../../../../../components/Editor/index.vue";
import debounce from "lodash/debounce";

import {
  getContractTypeListApi,
  editContractTypeListApi,
  getscontractListApi,
  getscontractgetInfoApi,
  editscontractinfoApi,
  deletecontractListApi,
  addscontractListApi,
  addContractTypeListApi,
  getfactorListApi,
  editfactorListApi,
  addfactorListApi,
  deletfactorListApi,
  uploadContractFilesApi
} from "@/wss/newApi_3-24/base/contractType";

export default {
  name: "contract",
  components: {
    NewCard,
    ComAddButton,
    ComAddButtonTwo,
    Comdrawer,
    WangEditor,
    ComTable,
    SubBtn,
    Editor,
  },
  data() {
    return {
      key: "",
      currentValue: "",
      vshow: false,
      direction: "rtl",
      //是否显示分页
      isShowpagination: false,
      //高亮
      statusactiv: -1,
      border: false,
      //左侧菜单高亮
      highlight: true,
      //查合同抽屉是否显示
      content: false,
      //查要素侧抽屉是否显示
      factor: false,
      //合同名称抽屉是否显示
      contentname: false,
      contenttitle: "", //合同title
      //一级分类类型index
      currentIndex: "",
      //二级分类index
      sencendIndex: "",
      //一级类型tag显示输入框
      tagInput: "",
      //一级分类数据集合
      tableData: [],
      //二级分类的数据集合
      scendtable: [],
      //合同名称的数据集合
      thridtable: [],
      //合同信息数据集合
      contractList: [],
      contractnameid: "",
      //文本域的数据集合
      textContent: [],
      //合同信息文本域
      currentContent: [],
      // 合同名称的info索引、
      currentContentindex: "",
      row: "",
      col: "",
      tmpRow: {}, //合同名称
      //合同名称新增文本域
      textContentname: [],
      //滑块切换状态
      statusinfo: true,
      //一级类别当前选中pid
      fristData: {}, //当前选择的一级类别数据
      fristid: "", //一级id
      fristName: "",
      //二级类别当前选中pid
      secendid: "", //二级id
      secendData: {}, //当前选择的二级类别数据
      secendName: "",
      //收集输入框的数据
      inputValue: {},
      //双击一级类别tag显示输入框
      tagInput: "",
      //判断二级类型是否显示
      jobVisible: false,
      jobTitleValue: "",
      //双击二级类别tag显示输入框
      jobInput: "",
      //单击图标当前编辑的id和base64图片字符串
      editDbIcon: {
        id: "",
        base64: "",
        // type: "",
        // status: "",
      },
      tabClickIndex: null, // 点击的单元格
      tabClickLabel: "", // 当前点击的列名
      //合同名称新增表单
      contentForm: {
        name: "",
        info: [],
        type: "",
        pid: "",
      },
      //要素表格数据
      factortable: [],
      // 表格配置
      config: {
        // border: true,
        isAdd: false,
        loading: false,
      },
      tableModes: [
        // {
        //   label: "要数编号",
        //   mode: "number",
        //   width: 100,
        //   showOverflowTooltip: true,
        // },
        {
          label: "要素名称",
          mode: "element",
          width: 100,
          showOverflowTooltip: true,
        },
        {
          label: "要素同义词",
          mode: "synonym",
          width: 100,
          showOverflowTooltip: true,
        },

        {
          label: "要素说明",
          mode: "keypoint",
        },
      ],
      // 表格分页参数
      pageing: { pageNum: 1, pageSize: 10, total: 0 },
      //编辑的信息
      textarea: "",
      //要素刪除id
      ysid: "",
      factorid: "", //合同名稱要素id,
      //要素详情信息存储、
      infotable: [],
      //表单
      ruleForm: {
        // element: "",
        // synonym: "",
        // keypoint: "",
      },
      contenrules: {
        name: [{ required: true, message: "请输入合同名称", trigger: "blur" }],
        info: [{ required: true, message: "请填写合同内容", trigger: "blur" }],
      },
      rules: {
        element: [{ required: true, message: "要素名称", trigger: "blur" }],
        synonym: [{ required: true, message: "要素同义词", trigger: "blur" }],

        keypoint: [
          { required: true, message: "请填写要素说明", trigger: "blur" },
        ],
      },

      // 上传合同的文件列表
      contractFiles:[],

      thanWordShow: false,// 合同类别对比词抽屉
      thanWordInput:'',// 合同类别对比词输入的内容
    };
  },
  mounted() {
    // this.selectChangeFirst(1);
  },
  created() {
    this.getContractTypefn();
  },
  watch: {
    content: {
      handler() {
        console.log();
        this.key = Math.random();
        // console.log("gaodingl");
        this.$forceUpdate();
      },
      deep: true,
    },
  },
  methods: {
    //一级类别 input-new-tag"
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    //一级类别 input确认之后执行的函数
    handleInputConfirm(row) {
      let data = {
        pid: "1",
        type: "1", //一级类别的状态为1，二级为2
        name: row.name,
        base64: row.base64,
        status: "0",
      };
      this.addContractTypeListfn(data);
    },

    //一级类别 双击显示输入框
    dblclickInput(index) {
      console.log(index);
      setTimeout(() => {
        this.$refs.dbtagInput[0].focus();
      }, 50);
      this.tagInput = index;
    },

    //一级类别 失去焦点或者回车修改名称
    handleInput(type, typeName) {
      console.log();
      let data = {
        id: type.id,
        name: type.name,
        status: type.status,
        pid: type.pid,
        type: type.type,
      };
      if (!typeName) {
        this.$message.error("输入值不能为空！");
        return;
      }
      this.tagInput = "";
      //修改的接口
      this.editContractTypefn(data);
    },

    //二级类别 双击显示输入框
    dblclickJobInput(index) {
      console.log(index);
      setTimeout(() => {
        this.$refs.dbJobInput[0].focus();
      }, 50);
      this.jobInput = index;
    },

    //二级类别 失去焦点或者回车修改名称
    handleJobInput(row, rowname) {
      // console.log(row, "11111222");
      let rows = {
        id: row.id,
        name: row.name,
        status: row.status,
        pid: row.pid,
        type: "2",
      };
      if (!rowname) {
        this.$message.error("输入值不能为空！");
        return;
      }
      this.jobInput = "";
      //修改的接口
      this.editContractTypefn(rows);
    },

    //合同名称的修改
    tableRowClassName({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex;
    },

    // 添加明细原因 row 当前行 column 当前列
    tabClick(row, column, cell, event) {
      this.tabClickIndex = row.index;
      this.tabClickLabel = column.label;
    },

    // 失去焦点初始化
    async inputBlur(row) {
      let { code } = await editscontractinfoApi(row);
      if (code == 200) {
        this.$message({
          message: "操作成功",
          type: "success",
        });

        // this.getsContractInfoApifn(row.id);
      }
      this.tabClickIndex = null;
      this.tabClickLabel = "";
    },

    async handleJobConfirm(row) {
      //一级类别的状态为1，type为1 pid为1，二级时type为2 pid等于一级类别的id
      let data = {
        type: "2",
        name: row.name,
        pid: this.fristid,
        // base64: row.base64,
        status: "0",
      };
      let result = await addContractTypeListApi(data);
      console.log(result);
      if (result.code == 200) {
        this.$message({
          message: "添加成功",
          type: "success",
        });
        //刷新模拟点击
        await this.getContractTypefn();
        this.onRowClick(this.tableData[this.currentIndex], this.currentIndex);
      } else {
        return Promise.reject(result.message);
      }
    },

    //通过getFile方法获取文件信息
    getFileId(type) {
      this.editDbIcon.id = type.id;
    },
    getFile(file, fileList) {
      //上传判断
      const isJPG = file.raw.type === "image/jpeg";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      //   return;
      // }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return;
      }

      if (fileList && fileList.length > 1) {
        fileList.shift();
      }
      this.imageUrl = file.url;
      this.getBase64(file.raw).then((res) => {
        const params = res;
        this.editDbIcon.base64 = params.split(",")[1];
        console.log(this.editDbIcon, "123");
        //修改的接口
        this.editContractTypefn(this.editDbIcon);
        // //延时执行刷新
        // setTimeout(() => {
        //   //更新专家类型职称列表
        //   this.getContractTypefn();
        // }, 50);
      });
    },

    //二级类别图片编辑
    getsecendFileId(type) {
      this.editDbIcon.id = type.id;
    },

    // 图片转base64编码：
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          // console.log(reader.result,'reader.result')
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },

    //获取合同类型
    async getContractTypefn() {
      let { code, rows } = await getContractTypeListApi();
      if (code != 200) return;
      this.tableData = rows;
      this.secendData = this.tableData[this.currentIndex]?.children[this.sencendIndex]// 获取当前的二级类别数据
      this.thanWordInput = this.tableData[this.currentIndex]?.children[this.sencendIndex]?.keywords// 获取当前的合同类别对比词
    },

    //类型编辑
    async editContractTypefn(data) {
      let { code, rows } = await editContractTypeListApi(data);
      if (code == 200) {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        await this.getContractTypefn(); //刷新数据
      } else {
        this.$message({
          message: msg,
          type: "error",
        });
      }
    },

    // 添加一级类型
    async addContractTypeListfn(data) {
      let result = await addContractTypeListApi(data);
      console.log(result);
      if (result.code == 200) {
        this.$message({
          message: "添加成功",
          type: "success",
        });
        this.getContractTypefn();
      } else {
        return Promise.reject(result.message);
      }
    },

    //合同信息的id查询
    async getsContractInfoApifn(id) {
      let { code, data } = await getscontractgetInfoApi(id);
      if (code != 200) return;
      this.contractList = data;
    },

    //合同名称查询
    async getscontractListApi(id) {
      console.log(id, "id");
      let { code, data } = await getscontractListApi({ contractTypeId: id });
      if (code != 200) return;
      this.thridtable = data.rows;
      
      this.contractnameid = this.thridtable.length && this.thridtable[0].id;
    },
    //合同内容的新增
    // async addContentname(item) {
    //   const editor = this.$refs.editor.Quill.editor.delta.ops[0];
    //   if (editor.insert != "\n") {
    //     let neweditor = editor.insert.replace(/<[^>]+>|&[^>]+;/g, "").trim();
    //     item.info.push(neweditor);
    //     item.type = "3";
    //     item.contractType = {
    //       parentId: this.fristid,
    //       parentContent: this.fristName,
    //       id: this.secendid,
    //       content: this.secendName,
    //     };
    //     let { code, msg } = await addscontractListApi(item);
    //     if (code != 200) return;
    //     this.$message({
    //       message: msg,
    //       type: "success",
    //     });
    //     this.contentname = false;
    //     this.getscontractListApi(this.secendid);
    //   } else {
    //     this.$message({
    //       message: "请输入新增信息",
    //       type: "warning",
    //     });
    //   }
    // },

    //合同信息的显示隐藏｛
    contentClose() {
      this.content = false;
      //清空原本赋值数据
      this.contractList = [];
      this.contenttitle = "";
      this.currentContent.length=0
      this.$refs.wangEditor.setEditorDataFn("");
    },

    //要素信息显示隐藏
    factorClose() {
      this.factor = false;
    },

    contentnameClose() {
      // this.$refs.textContentname.setEditorDataFn("");
      // this.$refs.editor.Quill.editor.delta.ops[0].insert=""
      console.log(this.$refs.editor.Quill.editor.delta.ops[0].insert);
      this.contentname = false;
      this.contentForm = {};
    },

    addcontenname() {
      // this.$refs.wangEditor.$destroy();
      if (this.secendid !== "") {
        this.content = true;
      } else {
        this.$message({
          message: "请选择二级类别",
          type: "warning",
        });
      }
    },

    //点击一级类别某一行的数据
    onRowClick(row, index) {
      this.fristData = row
      this.fristid = row.id;
      this.fristName = row.name;
      this.currentIndex = index;
      this.scendtable = row.children;
      console.log(this.fristid, "this.fristpid");
      console.log(this.scendtable, "this.scendtable");
      console.log(row, "this.row");
    },

    //点击二级类别某一行的数据
    secendClick(jobTitle, index) {
      this.sencendIndex = index;
      
      this.secendData = jobTitle //当前选择的二级全部数据
      this.secendid = jobTitle.id; //当前选择的二级id
      this.secendName = jobTitle.name; //当前选择的二级标题

      // this.thanWordInput = this.secendData.keywords// 回显二级类别的keywords

      this.getscontractListApi(this.secendid);
      console.log(this.secendid, "this.fristpid");
    },

    //点击合同查询对应的数据
    contentlist(row) {
      console.log(row, "row");
      this.contenttitle = row.name;
      this.content = true;
      let id = row.id;
      this.getsContractInfoApifn(id);
    },

    //新增合同名称和信息
    contentbtn() {},

    //合同信息info的删除
    async deletecontractListAFn(query) {
      let { code, data } = await deletecontractListApi(query);
      if (code != 200) return;
      this.getsContractInfoApifn(query.id);
      this.$message({
        message: "删除成功",
        type: "success",
      });
    },

    //删除某一条合同信息
    deletinfo(i) {
      const _this = this;
      // console.log(this.currentContentindex,"shnchu")
      if (_this.currentContentindex !== "") {
        let query = {
          id: i.id,
          index: this.currentContentindex,
        };
        //清空文本域
        this.$refs.wangEditor.setEditorDataFn("");
        this.deletecontractListAFn(query);
      } else {
        this.$message({
          message: "请选择删除的数据",
          type: "warning",
        });
      }
    },

    //合同内容新增编辑信息
    addscontractinfo: debounce(async function(item){
      let content = this.$refs.wangEditor.getEditorDataFn();
      if (item.id) {
        console.log("有ID吗？");
        if (this.currentContent.length) {
          item.name = this.contenttitle;
           let newlist=content.replace(/<p>/g,'')
           item.info[this.currentContentindex] = newlist.replace(/<[^>]+>|&[^>]+;/g, "\r").trim();
          let { code } = await editscontractinfoApi(item);
          if (code == 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.$refs.wangEditor.setEditorDataFn("");
            this.currentContentindex = "";
            this.currentContent = [];

          //   this.getscontractListApi(this.secendid);
          //  setTimeout(() => {
          //   this.getsContractInfoApifn(this.contractnameid);
          // }, 500);
        
          }
        } else {
          console.log("这个是新增吧");
          if (content) {
            let newlist=content.replace(/<p>/g,'')
            item.info.push(newlist.replace(/<[^>]+>|&[^>]+;/g, "\r").trim());
              // item.info.push(content)
            let { code, msg } = await addscontractListApi(item);
            if (code == 200)
              this.$message({
                message: msg,
                type: "success",
              });
            this.$refs.wangEditor.setEditorDataFn("");
            this.getsContractInfoApifn(item.id);
          } else {
            this.$message({
              message: "填写新增的信息",
              type: "warning",
            });
          }
        }
      } else {
          console.log("这个是新增合同名称吧");
        //新增合同名称
        if (this.contenttitle != "") {
          let formdata = {
            name: this.contenttitle,
            contractType: {
              parentId: this.fristid,
              parentContent: this.fristName,
              id: this.secendid,
              content: this.secendName,
            },
          };
          formdata.info = [];
          // let newcontent = content.replace(/<[^>]+>|&[^>]+;/g, "").trim();
          formdata.info.push(content);
          let { code, msg } = await addscontractListApi(formdata);
          if (code == 200)
            this.$message({
              message: msg,
              type: "success",
            });
          // this.contenttitle = "";
          // 关闭弹窗清空数据
          this.contentClose();
          this.$refs.wangEditor.setEditorDataFn("");
          this.getscontractListApi(this.secendid);
          setTimeout(() => {
            this.getsContractInfoApifn(this.contractnameid);
          }, 500);
        } else {
          this.$message({
            message: "填写新增的信息",
            type: "warning",
          });
        }
      }
    },600),
 
    factorlistclick(row) {
      this.factorid = row.id;
      this.factorlisttable(this.factorid);
    },

    //要素信息查询
    async factorlisttable() {
      let { pageNum, pageSize } = this.pageing;
      let data = {
        pageNum,
        pageSize,
        contractId: this.factorid,
      };

      let { rows, code, total } = await getfactorListApi(data);
      if (code != 200) return;
      this.factortable = rows;
      this.pageing.total = total;
    },

    // 要素表格行点击
    RowClickFn(row) {
      this.ruleForm = JSON.parse(JSON.stringify(row));
      this.ysid = row.id;
      console.log(row, "this.ysid");
    },

    //点击合同信息
    clickinfo(item, index) {
      const _this = this;
      _this.currentContentindex = index;
      _this.statusactiv = index;
      _this.currentContent = [item.info[index].replace(/\r/g,'</p><p>')];
    },

    //要素信息编辑
    async editfactorListfn() {
      let editForm = this.ruleForm;
      let { code, msg } = await editfactorListApi(editForm);
      if (code == 200) {
        this.$message({
          message: msg,
          type: "success",
        });
        this.ruleForm = {};
        this.ysid=""
        this.factorlisttable(this.factorid);
      } else {
        this.$message({
          message: msg,
          type: "error",
        });
      }
    },

    //要素的新增
    addfactorListApifn: debounce(async function(){
      let data = {
        typeId: "2",
        type: "2",
        contractId: this.factorid,
      };
      let editForm = Object.assign(this.ruleForm, data);
      console.log(editForm, "editForm");
      let { code, msg } = await addfactorListApi([editForm]);
      if (code == 200) {
        this.$message({
          message: msg,
          type: "success",
        });
        this.ruleForm = {};
        this.ysid = "";
        console.log(this.factorid, "123");
        this.factorlisttable(this.factorid);
      } else {
        this.$message({
          message: msg,
          type: "error",
        });
      }
    },500),

    //删除某一条要素
    async deleteinfo(row) {
      if (!this.ysid == "") {
        let { code, msg } = await deletfactorListApi({ id: this.ysid });
        if (code == 200) {
          this.$message({
            message: msg,
            type: "success",
          });
          this.factorlisttable(this.factorid);
          this.ruleForm = {};
          this.ysid = "";
        }
      } else {
        this.$message({
          message: "请点击删除数据",
          type: "warning",
        });
      }
    },

    //复制要素的函数
    copyToClipboard(textToCopy) {
      // navigator clipboard 需要https等安全上下文
      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        return navigator.clipboard.writeText(textToCopy);
      } else {
        // 创建text area
        let textArea = document.createElement("textarea");
        textArea.value = textToCopy;
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = "absolute";
        textArea.style.opacity = 0;
        textArea.style.left = "-999999px";
        textArea.style.top = "-999999px";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? res() : rej();
          textArea.remove();
        });
      }
    },

    // 粘贴要素的函数
    pasteToClipboard(textToCopy) {
      // navigator clipboard 需要https等安全上下文
      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        return navigator.clipboard.writeText(textToCopy);
      } else {
        // 创建text area
        let textArea = document.createElement("textarea");
        textArea.value = textToCopy;
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = "absolute";
        textArea.style.opacity = 0;
        textArea.style.left = "-999999px";
        textArea.style.top = "-999999px";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? res() : rej();
          textArea.remove();
        });
      }
    },

    //复制要素
   async copy() {
      //清空要素from
      this.ruleForm = {};
      // 请求拿到所有的要素
      let { rows } = await getfactorListApi({
        contractId: this.factorid,
      });
      if (rows.length) {
        let temp = JSON.stringify(rows);
        // navigator.clipboard.writeText(temp);
        this.copyToClipboard(temp);
        this.$message({
          message: "复制成功",
          type: "success",
        });
      } else {
        this.$message({
          message: "数据为空",
          type: "warning",
        });
      }

      // let clipboard = new Clipboard(".copy-email");
      // clipboard.on("success", (e) => {
      //   console.log(e, "eeeee");
      //   that.$message.success("复制成功！");
      //   clipboard.destroy();
      // });
      // clipboard.on("error", (e) => {
      //   that.$message.error("复制失败，请手动复制！");
      //   clipboard.destroy();
      // });
    },

    //粘贴
    async paste() {
      // this.factortable.forEach((item) => {
      //   let p = new Promise((resolve, reject) => {
      //     setTimeout(function () {
      //       resolve(resolve(deletfactorListApi()));
      //     }, 10);
      //   });
      //   arr.push(p);
      // });
      Promise.all(
        this.factortable.map(
          async ({ id }) =>
            await deletfactorListApi({
              id,
            })
        )
      ).then(async () => {
        // Promise.all(
        //   this.factortable.map(
        //     // es 结构 ，不用结构是item（元素的每一个元素）
        //     ({
        //       typeId = "",
        //       contractId = "",
        //       element = "",
        //       synonym = "",
        //       keypoint = "",
        //     }) => {
        //       return addfactorListApi({
        //         typeId,
        //         contractId,
        //         element,
        //         synonym,
        //         keypoint,
        //       });
        //     }
        //   )
        // );
        this.factortable = JSON.parse(await navigator.clipboard.readText());
        this.factortable.forEach((item) => {
          //  Reflect.defineProperty(item,"")
          item.contractId = this.factorid;
          delete item.id;
        });
        let { code, msg } = await addfactorListApi(this.factortable);

        if (code != 200) return;
        this.$message({
          type: "success",
          message: msg,
        });
        this.factorlisttable(this.factorid);
      });
    },

    //编辑提交
    submitForm: debounce(function(formName){
      if (this.ysid) {
        this.editfactorListfn();
      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addfactorListApifn();
          } else {
            // this.$message({
            //   message:"",
            //   type: "error",
            // });
          }
        });
      }
    },600),

    //重置
    resetForm() {
      this.ruleForm = {
        element: "",
        keypoint: "",
        synonym: "",
      };
      this.ysid = "";
    },

    // 当前页发生改变时
    handleCurrentChange(pageNum) {
      this.pageing.pageNum = pageNum;
      this.factorlisttable();
    },

    // 页容量发生改变
    handleSizeChange(pageSize) {
      this.pageing.pageSize = pageSize;
      this.factorlisttable();
    },
    // ---------------------合同上传---------------------
    // 上传合同的回调
    uploadContract(file,fileList,jobTitle,index){
      //上传判断
      const isFormat = file.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      const isLt2M = file.raw.size / 1024 / 1024 < 20;

      if (!isFormat) {
        this.$message.error("仅支持DOCX格式!");
        return;
      }else{
        if (!isLt2M) {
          this.$message.error("上传文件大小不能超过20MB!");
          return;
        }else{
          if (fileList && fileList.length > 1) {
            fileList.shift(); 
          }
          this.contractFiles.push(file);//把当前上传的文件添加到图片列表里面
          this.uploadContractFiles(jobTitle,index)
        }
      }
    },

    // 上传合同的接口 防抖
    uploadContractFiles: debounce(async function(jobTitle,index){
      // 过滤父类别的name
      let parent = this.tableData.find(item=>{
        return item.id == jobTitle.pid
      })

      let formData = new FormData();
      formData.set("id", jobTitle.id); //类别id
      formData.set("content", jobTitle.name); //类别
      formData.set("parentId", jobTitle.pid); //父类别ID
      formData.set("parentContent", parent.name); //父类别
      // 添加合同文件.
      this.contractFiles.forEach(item=>{
        formData.append("files", item.raw);
      })
      this.$message({message: '正在上传，请稍等！',type: 'success'});
      let result = await uploadContractFilesApi(formData)
      if(result.code==200){
        this.$message({message: '上传成功！',type: 'success'});
        this.secendClick(jobTitle, index) //刷新页面
        this.contractFiles = []//清空之前的上传的合同数据
      }
    },500),
    // ---------------------合同上传---------------------end

    // ---------------------合同类别对比词---------------------
    // 点击对比词按钮
    clickThanWords(){
      this.thanWordShow = true
    },
    
    // 关闭对比词按钮抽屉
    thanWordClose(){
      this.thanWordShow = false
    },

    // 合同对比词点击确定
    async thanWordConfirm(){
      // 判空
      if (!this.secendData.keywords) {
        this.$message.error("输入值不能为空！");
        return;
      }
      // 把所有英文逗号转为中文逗号
      let keywords = this.secendData.keywords.replace(/,/ig,'，')

      let data = {
        id: this.secendid,
        keywords: keywords,
      };
      
      await this.editContractTypefn(data);//修改的接口
    },

    // 点击取消按钮
    thanWordCancel(){
      this.thanWordShow = false
    },
    
    // ---------------------合同类别对比词---------------------end

  },
  computed: {
    //左侧下拉框筛选
  },
};
</script>

<style  scoped>
.contractTmp-box {
  height: calc(100% - 60px);
}
.label-box-content {
  height: 100%;
}
.el-input-number--mini {
  width: 100px;
}
.el-card >>> .top {
  border-bottom: 0;
  padding-top: 0;
}
.el-card >>> .el-card__body {
  position: relative;
  height: 100%;
}
.el-card >>> .el-card__body > div {
  padding-top: 0 !important;
  height: 92%;
  overflow-y: auto;
}
.corrExpert .el-card >>> .el-card__body > div {
  overflow-y: initial;
}
.el-card >>> .el-card__body > div::-webkit-scrollbar {
  width: 0;
}

.el-row,
.el-card,
.el-col {
  height: 100%;
  margin-bottom: 0;
}
.label-box-content >>> h1 {
  margin: 0;
  padding: 20px 0 15px 0;
}
.label-box-content >>> .top::after {
  height: 0;
}

/* 左侧菜单 */
.leftMenu {
  margin-top: 10px;
  margin-bottom: 30px;
}
.el-tag {
  display: flex;
  justify-content: space-between;
  position: relative;
  background-color: #f8f8f8;
  border-color: #f8f8f8;
  height: 40px !important;
  line-height: 40px !important;
  font-size: 16px;
  width: 100%;
  margin-right: 3%;
  margin-bottom: 10px;
  color: #333;
}
.el-tag svg{
  color: #999;
  font-size: 18px;
  margin-right: 10px;
  cursor: pointer;
}
.el-tag p {
  margin: 0;
  display: inline-block;
}
.el-tag > .tag-icon {
  position: absolute;
  width: 30px;
  height: 30px;
  right: 10px;
  top: 5px;
  margin: 0;
}
.el-tag > .tag-icon img {
  width: 25px;
  height: 25px;
  object-fit: cover;
  transition: all 0.3s;
}
.el-tag > .tag-icon:hover img {
  transform: scale(1.8);
}
.el-tag .el-input {
  width: 120px;
}
.el-tag .el-input >>> .el-input__inner {
  height: 30px;
  line-height: 30px;
  padding-left: 8px;
  padding-right: 10px;
}

.el-tag.tagActive {
  background-color: #1890ff;
  color: #fff;
}
.el-tag >>> .el-icon-close {
  font-size: 20px;
  height: 20px;
  width: 20px;
  line-height: 20px;
  color: #f56c6c;
}
.el-tag >>> .el-icon-close:hover {
  background-color: #f56c6c;
  color: #fff;
}

.el-tag .upload-icon .el-icon-upload{
  color: #999;
  font-size: 20px;
}
.el-tag.tagActive svg,
.el-tag.tagActive .upload-icon .el-icon-upload{
  color: #fff;
}

.el-table >>> table {
  width: 100% !important;
  table-layout: fixed !important;
  font-size: 16px;
}
.el-table >>> .el-table__body tr.current-row > td {
  background-color: #1890ff;
  color: #fff;
}
.el-table >>> .el-table__header-wrapper th,
.el-table >>> .el-table__fixed-header-wrapper th {
  background-color: #f8f8f8 !important;
  padding: 0;
}
.el-table >>> th.is-leaf,
.el-table >>> td {
  border-bottom: 0;
  padding: 8px 0;
}
.el-table >>> th.is-leaf {
  padding: 4px 0;
}
::v-deep .el-table__body .el-table__row {
  background-color: #f8f8f8;
}

::v-deep .el-table__body {
  /*  水平间距 */
  /* -webkit-border-horizontal-spacing: 13px;  */
  /* // 垂直间距 */
  -webkit-border-vertical-spacing: 10px;
}

.el-table .cell {
  margin: 10px;
}

.el-table::before {
  height: 0;
}
.button-new-tag {
  position: absolute;
  bottom: 0;
  left: 0;
  border: 0;
  display: block;
  width: 100%;
  font-size: 16px;
  padding: 15px 20px;
  background-color: #f8f8f8;
  border-top: 1px solid #e6ebf5;
}
.input-new-tag {
  position: absolute;
  bottom: 0;
  left: 0;
}
.leftMenu .leftSearch {
  position: absolute;
  right: 20px;
  top: 10px;
  z-index: 9;
}
.el-col-24 {
  margin-top: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e6ebf5;
}

.btninfo {
  position: absolute;
  top: 15px;
  right: 20px;
}
.btn {
  /* float:right; */
  margin: 10px 0;
}
.btnrow {
  float: right;
  margin: 10px;
}

.edit-box {
  float: right;
  margin-right: 20px;
}
/* 右侧抽屉 */
.inputtitle {
  padding: 10px 20px;
}
.wangeditor {
  padding: 0px 20px;
}
.businTalbe {
  margin-bottom: 40px;
}
.yasuinfo {
  height: calc(100% - 20px);
  padding: 0 20px;
}
.infoExpert {
  height: 100%;
}
.infoExpert .perInfo {
  margin-top: 20px;
}
.editmain {
  height: 100%;
}
.editmain .lineItem {
  height: 92%;
}
.drawerMain {
  padding: 0 20px;
  height: calc(100% - 20px);
}

.drawerMain .el-tag {
  width: 100%;
  height: auto !important;
  white-space: initial;
}
.drawerMain .input-new-tag {
  margin-bottom: 15px;
}
.drawerMain >>> .el-card__body {
  padding: 0;
}
.drawerMain .lineItem .divinfo {
  padding: 10px 20px;
  border-bottom: 1px solid #ccc;
}

.drawerMain >>> .el-card__body .top {
  padding: 0 25px;
}
/* 點擊合同高亮 */
.isbgc {
  background-color: #f8f8f8;
}
.classMode .el-tag {
  width: 30%;
}
.copypaste {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border: 0;
  display: block;
  width: 100%;
  font-size: 16px;
  padding: 10px 15px;
  background-color: #f8f8f8;
  border-top: 1px solid #e6ebf5;
}
.copypaste .el-button--medium {
  /* flex: 1; */
  width: 48%;
  border: none;
  background: none;
}

.hetongbtn {
  position: absolute;
  bottom: 0;
  left: 0;
  border: 0;
  display: block;
  width: 100%;
  font-size: 16px;
  padding: 15px 20px;
  background-color: #f8f8f8;
  border-top: 1px solid #e6ebf5;
}

/* 悬浮按钮 */
.subBtn {
  padding: 10px 30px;
  z-index: 10002;
}

.message-zindex {
  z-index: 10000 !important;
}

/* 抽屉样式 */
.contractTmp-box >>> .el-drawer__header {
  display: flex;
  margin: 0 20px;
  margin-bottom: 10px;
  padding: 0;
  border-bottom: 0.5px solid #dfe4ed;
}
.contractTmp-box >>> .el-drawer__header .el-button--medium {
  font-size: 18px;
  font-weight: bold;
  color: #2e3f5e !important;
}
.contractTmp-box >>> .el-drawer__body{
  height: calc(100% - 85px);
}
/* 抽屉样式 end */

.title-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.title-box .icon {
  width: 7px;
  margin-right: 8px;
}
.title-box .titile {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
}
.title-box span {
  color: #2e3f5e;
}
.left {
  width: 70%;
  overflow: hidden;
}
.el-form .demo-ruleForm {
  margin-top: 10px;
}

/* 合同对比词样式 */
.thanWordBox{
  margin: 0 30px;
}
.thanWordBox .thanWordInput >>> .el-textarea__inner{
  font-family: Microsoft Yahei;
}
</style>